<?php
namespace app\common\validate;
class Message extends \think\Validate
{
    protected $rule = [
        'name'  => 'require',
        'telephone'   => 'require|checkTel|unique:message,telephone^account_id',
        'building' => 'require',
        'sex' => 'require',
        'status' => 'require|checkStatus',
    ];

    protected $message = [
        'name.require' => '用户名不能为空',
        'telephone.require' => '手机号不能为空',
        'telephone.unique' => '你已录入该手机号',
        'sex.require' => '性别不能为空',
        'building.require' => '意向楼盘不能为空',
        'status.require' => '跟进状态不能为空',
    ];

    //用户电话重复检查
    protected function checkTel($value,$rule,$data)
    {
        if (!isTelephone($value))
            return '手机格式不正确';
        //不能录如转介过来的手机号,新增
        if (!$data['id']){
            $mark = 1;
        }
        //保存
        else{
            $userInfo = \app\common\model\Message::where('id',$data['id'])->find();
            if ($userInfo['account_id'] == $data['account_id'])
                $mark = 1;
        }
        if ($mark){
            $allTel = \app\common\model\Transfer::withTrashed()->with('messageInfo')->where('to_account_id',$data['account_id'])->select()->toArray();
            $allTel = array_column(array_column($allTel,'message_info'),'telephone');
            if (in_array($value,$allTel))
                return '不能录入转介过来的客户';
        }

        return true;

    }

    //检查用户跟进状态
    protected function checkStatus($value,$rule,$data){
        if ($value ==  '已买')
            return '无权修改状态为已买';
        if ($data['id']){
            $info = \app\common\model\Message::where('id',$data['id'])->find();
            if ($info['status'] =='已买')
                return '已买状态无权修改';
        }
        //已定用户，前置字段检查
        if ($value =='已定'){
            //保存
            if ($data['id']){
                //判断有没有相同手机号标记已定
                $findMap[] = ['telephone','eq',$info['telephone']];
                $findMap[] = ['status','eq','已定'];
                $check = \app\common\model\Message::where($findMap)->find();
                if ($check)
                    return '该用户已经被其他经纪人标记为已定';

                if (!$data['price'])
                    return '成交价格不能为空';
                if ($data['house1'] == null)
                    return '室不能为空';
                if ($data['house2'] == null)
                    return '厅不能为空';
                if ($data['house3'] == null)
                    return '卫不能为空';
                if ($data['house4'] == null)
                    return '厨不能为空';
                if ($data['number'] == null)
                    return '房号不能为空';

                $checkImg = \app\common\model\Deal::where('message_id',$data['id'])->find();
                if (!$checkImg)
                    return '已定状态，必须上传成交凭证';
                return true;
            }

        }
        return true;
    }

}